package org.mysterylab.utopiaframework.commons.compass.service;

import org.apache.commons.lang.StringUtils;
import org.compass.gps.CompassGps;
import org.compass.spring.web.mvc.AbstractCompassCommandController;
import org.compass.spring.web.mvc.CompassIndexCommand;
import org.compass.spring.web.mvc.CompassIndexController;
import org.compass.spring.web.mvc.CompassIndexResults;
import org.springframework.beans.factory.InitializingBean;

/**
 * 仿照 {@link CompassIndexController} 中的代码, 构建一个创建索引的 Service,
 * 这样在某些非 Spring MVC 的场合(比如 Struts) 中可以让 Action 中调用该 Service
 * 来完成创建索引的任务. 比如在 IndexAction.java 中可以这样写(SSH 架构):
 * <pre>
 *  public class IndexAction extends org.apache.struts.actions.DispatchAction implements InitializingBean {
 *      private Compass compass;
 *      
 *      public void afterPropertiesSet() throws Exception {...}
 *      
 *      // 创建索引的方法, 主要是: getCompassGps().index();
 *      public CompassIndexResults index() {
 *          long time = System.currentTimeMillis();
 *          getCompassGps().index();
 *          time = System.currentTimeMillis() - time;
 *          CompassIndexResults indexResults = new CompassIndexResults(time);
 *          return indexResults;
 *      }
 *      
 *      // 调用 index() 方法创建索引并返回正确的显示页面
 *      public ActionForward doIndex(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
 *          CompassIndexResults indexResults = index();
 *          request.setAttribute("indexResults", indexResults);
 *          return mapping.findForward(Constants.SUCCESS_KEY);
 *      }
 *  }
 * </pre>
 * 
 * @author zhouych
 * @see CompassIndexController
 * @see AbstractCompassCommandController
 */
public class CompassIndexService implements InitializingBean {
	
	/**
	 * 用来把不同的数据源与 Compass 集成, 支持 JPA, Hibernate, OJB, JDO 和 iBatis.
	 * 主要用来保持索引库与数据库的同步, 省去了每次数据库更新后的手动创建索引的麻烦
	 */
	private CompassGps compassGps;

	@Override
	public void afterPropertiesSet() throws Exception {
		if (compassGps == null) {
			throw new IllegalArgumentException("Must set the compassGpd property");
		}
	}

	/**
	 * 建立索引的接口.
	 * 
	 * @param command
	 *            如果 doIndex 为 "true", 则执行构建索引, 并将构建耗时封装入 {@link CompassIndexResults} 中. 否则, 不做任何操作并返回null
	 * @return
	 * @see CompassIndexResults
	 */
	public CompassIndexResults index(CompassIndexCommand command) {
		if (StringUtils.isBlank(command.getDoIndex())
				|| !command.getDoIndex().equalsIgnoreCase("true")) {
			return null;
		}

		long time = System.currentTimeMillis();
		// 建立索引
		getCompassGps().index();
		time = System.currentTimeMillis() - time;
		
		// 把索引创建的耗时加入结果集中, 当然还可以加入其他内容
		CompassIndexResults indexResults = new CompassIndexResults(time);

		return indexResults;
	}

	public CompassGps getCompassGps() {
		return compassGps;
	}

	public void setCompassGps(CompassGps compassGps) {
		this.compassGps = compassGps;
	}
}
